package com.qd.extcamclientv2;

import java.io.File;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class MainActivity extends Activity implements View.OnClickListener {
	public static final String TAG = "ExtCamClientV2";
	private void _log(String log) {
		Log.i(TAG, "MainActivity: " + log);
	}

	public static String EXTCAM_DIR = "";;

	private WakeLock mWakeLock = null;
	private ArrayList<String> mListItems = null;
	private ArrayAdapter<String> mListAdapter = null;
	private ListView mListView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		findViewById(R.id.btn_refresh).setOnClickListener(this);
		findViewById(R.id.btn_delete).setOnClickListener(this);
		findViewById(R.id.btn_delete_all).setOnClickListener(this);
		findViewById(R.id.btn_play_file).setOnClickListener(this);

		findViewById(R.id.btn_device_connect).setOnClickListener(this);
		findViewById(R.id.btn_exit).setOnClickListener(this);

		EXTCAM_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ExtCamData";
		File path = new File(EXTCAM_DIR);
		if (false == path.isDirectory()) {
			path.mkdirs();
		}
		_log(EXTCAM_DIR);

		mWakeLock = ((PowerManager)getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.FULL_WAKE_LOCK, "WakeAlways");
		mWakeLock.acquire();	// 항상 화면이 켜지도록 수정

		mListItems = new ArrayList<String>();
		mListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, mListItems);
		mListView = (ListView)findViewById(R.id.lst_file);
		mListView.setAdapter(mListAdapter);
		mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mListView.setOnItemClickListener(mItemClickListener);

		refreshFileList();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(this).setTitle(R.string.dlg_title_confirm)
		.setMessage(R.string.dlg_msg_exit).setCancelable(false)
		.setNegativeButton(R.string.dlg_btn_cancel, null)
		.setPositiveButton(R.string.dlg_btn_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		})
		.show();

		//super.onBackPressed();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		mWakeLock.release();

		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View arg0) {
		int nId = arg0.getId();
		_log("onClick(" + nId + ")");

		switch (nId) {
		case R.id.btn_refresh:
			refreshFileList();
			break;
		case R.id.btn_delete:
			deleteFile(false);
			break;
		case R.id.btn_delete_all:
			deleteFile(true);
			break;
		case R.id.btn_play_file:
			playFile();
			break;

		case R.id.btn_device_connect:
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityForResult(intent, 1);
			break;
		case R.id.btn_exit:
			new AlertDialog.Builder(this).setTitle(R.string.dlg_title_confirm)
			.setMessage(R.string.dlg_msg_exit).setCancelable(false)
			.setNegativeButton(R.string.dlg_btn_cancel, null)
			.setPositiveButton(R.string.dlg_btn_ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			})
			.show();
			break;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (1 == requestCode) {
			refreshFileList();
		}

		super.onActivityResult(requestCode, resultCode, data);
	}


	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
		}
	};

	private final static Comparator<String> myComparator = new Comparator<String>() {
		private final Collator collator = Collator.getInstance();
		@Override
		public int compare(String object1, String object2) {
			//return collator.compare(object1, object2);	// 내림차순
			return collator.compare(object2, object1);	// 오름차순
		}
	};

	/**
	 * 
	 */
	private void refreshFileList() {
		mListItems.clear();

		File file = new File(EXTCAM_DIR);
		File[] files = file.listFiles();
		if (null != files) {
			for (int i=0; i<files.length; i++) {
				if (!files[i].isDirectory()) {
					mListItems.add(files[i].getName());
				}
			}
		}

		Collections.sort(mListItems, myComparator);
		mListView.clearChoices();
		mListAdapter.notifyDataSetChanged();
	}

	/**
	 * 
	 */
	private void playFile() {
		int nPos = mListView.getCheckedItemPosition();
		if (ListView.INVALID_POSITION != nPos) {
			File file = new File(EXTCAM_DIR, mListItems.get(nPos));
			if (file.exists()) {
				String fileName = file.getName();
				String fileExt = fileName.substring(fileName.length()-3, fileName.length());
				if (fileExt.equalsIgnoreCase("mp4")) {
					Intent intent = new Intent(this, PlayerActivity.class);
					intent.putExtra(PlayerActivity.EXTRA_FILENAME, file.toString());
					startActivity(intent);
				}
			}
		}
	}

	/**
	 * @param isAll
	 */
	private void deleteFile(boolean isAll) {
		if (isAll) {
			new AlertDialog.Builder(this).setTitle(R.string.dlg_title_confirm)
			.setMessage(R.string.dlg_msg_file_delete_all).setCancelable(false)
			.setNegativeButton(R.string.dlg_btn_cancel, null)
			.setPositiveButton(R.string.dlg_btn_ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					File file = new File(EXTCAM_DIR);
					File[] files = file.listFiles();
					if (files != null) {
						for (int i=0; i<files.length; i++) {
							if (!files[i].isDirectory()) {
								files[i].delete();
							}
						}
						refreshFileList();
					}
				}
			})
			.show();
		} else {
			final int nPos = mListView.getCheckedItemPosition();
			if (ListView.INVALID_POSITION != nPos) {
				new AlertDialog.Builder(this).setTitle(R.string.dlg_title_confirm)
				.setMessage(R.string.dlg_msg_file_delete).setCancelable(false)
				.setNegativeButton(R.string.dlg_btn_cancel, null)
				.setPositiveButton(R.string.dlg_btn_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						File file = new File(EXTCAM_DIR, mListItems.get(nPos));
						if (file.exists()) {
							file.delete();
							refreshFileList();
						}
					}
				})
				.show();
			}
		}
	}
}
